package com.snapan.controller;


import com.snapan.common.PageResult;
import com.snapan.entity.UserFile;
import com.snapan.service.UserFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户文件关联表控制器
 */
@RestController
@RequestMapping("/api/userfile")
public class UserFileController {

    @Autowired
    private UserFileService userFileService;

    /**
     * 获取用户文件列表
     */
    @GetMapping("/list")
     //TODO: 2025-09-04 userId应该从session获取，而不是前端传值，保证安全。
    public Map<String, Object> getList(@RequestParam int pageSize, 
                                      @RequestParam int pageNo, 
                                      @RequestParam int userId,
                                      @RequestParam int parentId,
                                      @RequestParam(required = false) Integer status,
                                      @RequestParam(required = false) String fileType) {
        Map<String, Object> result = new HashMap<>();
        try {
            PageResult<UserFile> page = userFileService.selectByPage(pageSize, pageNo, userId, parentId, fileType);
            result.put("success", true);
            result.put("data", page);
            result.put("message", "获取文件列表成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取文件列表失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 根据ID获取文件信息
     */
    @GetMapping("/{id}")
    public Map<String, Object> getById(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            UserFile userFile = userFileService.getById(id);
            if (userFile != null) {
                result.put("success", true);
                result.put("data", userFile);
                result.put("message", "获取成功");
            } else {
                result.put("success", false);
                result.put("message", "文件不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 添加用户文件关联
     */
    @PostMapping("/add")
    public Map<String, Object> add(@RequestBody UserFile userFile) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = userFileService.add(userFile);
            result.put("success", success);
            result.put("message", success ? "添加成功" : "添加失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "添加失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 更新用户文件关联
     */
    @PutMapping("/update")
    public Map<String, Object> update(@RequestBody UserFile userFile) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = userFileService.update(userFile);
            result.put("success", success);
            result.put("message", success ? "更新成功" : "更新失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 删除用户文件关联
     */
    @DeleteMapping("/{id}")
    public Map<String, Object> delete(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = userFileService.delete(id);
            result.put("success", success);
            result.put("message", success ? "删除成功" : "删除失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 根据用户ID和父目录ID获取文件列表
     */
    @GetMapping("/user/{userId}/parent/{parentId}")
    public Map<String, Object> getByUserAndParent(@PathVariable Long userId, @PathVariable Long parentId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<UserFile> fileList = userFileService.selectByUserAndParent(userId, parentId);
            result.put("success", true);
            result.put("data", fileList);
            result.put("message", "获取文件列表成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取文件列表失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 创建文件夹
     */
    @PostMapping("/create-folder")
    public Map<String, Object> createFolder(@RequestParam String folderName,
                                           @RequestParam Long userId,
                                           @RequestParam(required = false, defaultValue = "0") Long parentId) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 验证文件夹名称
            if (folderName == null || folderName.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "文件夹名称不能为空");
                return result;
            }
            
            // 检查文件夹名称是否包含非法字符
            if (folderName.contains("/") || folderName.contains("\\") || folderName.contains(":") || 
                folderName.contains("*") || folderName.contains("?") || folderName.contains("\"") || 
                folderName.contains("<") || folderName.contains(">") || folderName.contains("|")) {
                result.put("success", false);
                result.put("message", "文件夹名称包含非法字符");
                return result;
            }
            
            // 检查同级目录下是否已存在同名文件夹
            boolean exists = userFileService.checkFolderExists(userId, parentId, folderName.trim());
            if (exists) {
                result.put("success", false);
                result.put("message", "该文件夹已存在");
                return result;
            }
            
            // 创建文件夹
            UserFile folder = userFileService.createFolder(folderName.trim(), userId, parentId);
            if (folder != null) {
                result.put("success", true);
                result.put("data", folder);
                result.put("message", "文件夹创建成功");
            } else {
                result.put("success", false);
                result.put("message", "文件夹创建失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "创建文件夹失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 重命名文件或文件夹
     */
    @PostMapping("/rename")
    public Map<String, Object> renameFile(@RequestParam Long fileId,
                                         @RequestParam String newName,
                                         @RequestParam Long userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 验证新名称
            if (newName == null || newName.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "新名称不能为空");
                return result;
            }
            
            // 检查新名称是否包含非法字符
            if (newName.contains("/") || newName.contains("\\") || newName.contains(":") || 
                newName.contains("*") || newName.contains("?") || newName.contains("\"") || 
                newName.contains("<") || newName.contains(">") || newName.contains("|")) {
                result.put("success", false);
                result.put("message", "名称包含非法字符");
                return result;
            }
            
            // 获取文件信息
            UserFile userFile = userFileService.getById(fileId);
            if (userFile == null) {
                result.put("success", false);
                result.put("message", "文件不存在");
                return result;
            }
            
            // 检查权限（用户只能重命名自己的文件）
            if (!userFile.getUserId().equals(userId)) {
                result.put("success", false);
                result.put("message", "无权限重命名此文件");
                return result;
            }
            
            // 检查同级目录下是否已存在同名文件/文件夹
            boolean exists = userFileService.checkNameExists(userId, userFile.getParentId(), newName.trim(), fileId);
            if (exists) {
                result.put("success", false);
                result.put("message", "该名称已存在");
                return result;
            }
            
            // 执行重命名
            boolean success = userFileService.renameFile(fileId, newName.trim());
            if (success) {
                result.put("success", true);
                result.put("message", "重命名成功");
            } else {
                result.put("success", false);
                result.put("message", "重命名失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "重命名失败：" + e.getMessage());
        }
        return result;
    }


}
